<template>
  <ElRow class="add-photo">
    <ElCol :span="24">
      <div class="title-name">
        {{ name }}
      </div>
      <div class="img-container">
        <div class="product-image">
          <img v-if="imgUrl" :src="imgUrl" width="100%" />
          <img v-else-if="img" :src="img" width="100%" />
          <img v-else :src="defaultImage" width="100%" />
        </div>
        <ElUpload
          ref="uploadImg"
          class="avatar-uploader"
          :action="url.uploadImg"
          :headers="headers"
          :on-success="handleAvatarSuccess"
          :on-error="handleAvatarError"
          :on-progress="handleProgress"
          :name="'photo'"
          :data="{thumb: 300}"
          :list-type="'picture'"
          :show-file-list="false"
        >
          <ElButton
            slot="trigger"
            type="primary"
            class="upload-button"
            round
            plain
            :loading="imgLoading"
            >点击上传</ElButton
          >
        </ElUpload>

        <ElButton type="info" class="delete" plain round @click="handleRemove"
          >删除</ElButton
        >
        <ElDialog
          :class="s.sourceDialog"
          :visible.sync="dialogVisible"
          width="1000px"
          :show-close="false"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
        >
          <ElRow type="flex" justify="space-between">
            <ElCol :span="17">
              <img id="image" :src="imgUrl" width="100%" />
            </ElCol>
            <ElCol :span="6" :class="s.preview">
              <div class="docs-preview clearfix">
                <div class="img-preview preview-sm"></div>
              </div>
              <ElButton
                type="primary"
                :class="s.cancleUploadImg"
                round
                plain
                @click="dialogVisible = false"
                >取消</ElButton
              >
              <ElButton
                type="primary"
                :class="s.croperSubmit"
                round
                plain
                @click="upFile"
                >确定</ElButton
              >
            </ElCol>
          </ElRow>
          <div slot="title" :class="s.dialogTitle">
            <span :class="s.itemIcon"></span>裁切图片
          </div>
        </ElDialog>
      </div>
    </ElCol>
  </ElRow>
</template>

<script>
import Cropper from 'cropperjs';
import Cookie from 'js-cookie';
import {http, catchAppError} from '@/util';
import defaultImage from '@/assets/img/default.jpg';
import url from '@/config';

export default {
  props: {
    img: {
      type: String,
      default: ''
    },
    name: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      url,
      defaultImage,
      dialogVisible: false,
      cropper: null,
      headers: {
        token: Cookie.get('token')
      },
      imgUrl: '',
      thumbnail: '',
      imgLoading: false
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      if (res.code !== 1) {
        this.$message({
          message: res.msg,
          duration: 5000,
          type: 'error'
        });
        return;
      }
      this.imgUrl = URL.createObjectURL(file.raw);
      this.thumbnail = res.data.path;
      this.$emit('photoImgUrl', this.thumbnail);
      this.dialogVisible = true;
      setTimeout(() => {
        const image = document.getElementById('image');
        if (this.cropper) {
          this.cropper.destroy();
        }
        this.cropper = new Cropper(image, {
          aspectRatio: 4 / 3,
          preview: '.img-preview'
        });
      }, 0);
    },
    cropperImage() {
      const result = this.cropper.getCroppedCanvas();
      const dataurl = result.toDataURL('image/jpg');
      const filename = 'ss';
      const arr = dataurl.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      // eslint-disable-next-line no-plusplus
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {type: mime});
    },
    upFile() {
      const file = this.cropperImage();
      const data = new FormData();
      data.append('photo', file, 'photo');
      data.append('thumb', -750);
      http
        .post(url.uploadImg, data)
        .then(res => {
          this.imgLoading = false;
          this.$emit('imgLoading', this.imgLoading);
          this.imgUrl = res.data;
          this.thumbnail = res.path;
          this.$emit('photoImgUrl', this.thumbnail);
          this.dialogVisible = false;
        })
        .catch(catchAppError);
    },
    handleAvatarError(err) {
      this.imgLoading = false;
      catchAppError(err);
    },
    handleRemove() {
      this.thumbnail = '';
      this.imgUrl = '';
    },
    handleProgress() {
      this.imgLoading = true;
      this.$emit('imgLoading', this.imgLoading);
    }
  }
};
</script>

<style lang="scss">
@import '../../../node_modules/cropperjs/dist/cropper.css';
.add-photo {
  color: #333;
  .title-name {
    width: 100px;
    font-size: 16px;
    font-weight: bold;
    display: inline-block;
  }
}
.img-container {
  display: inline-block;
  vertical-align: top;
  position: relative;
  .product-image {
    width: 270px;
    height: 200px;
    // border: 1px dashed #666;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 25px;
    vertical-align: bottom;
  }
  .avatar-uploader,
  .delete {
    width: 104px;
    position: absolute;
    bottom: 0;
    left: 295px;
  }
  .upload-button {
    margin-bottom: 50px;
  }
}
</style>
<style lang="scss" module="s">
@import '@/assets/css/dialog.scss';
.preview {
  position: relative;
}
.croper-submit {
  position: absolute;
  width: 104px;
  bottom: 0;
  right: 0;
}
.cancle-upload-img {
  position: absolute;
  width: 104px;
  bottom: 0;
  right: 115px;
}
</style>

<style lang="scss">
.img-preview {
  max-width: 100%;
  float: left;
  margin-bottom: 0.5rem;
  margin-right: 0.5rem;
  overflow: hidden;
}

.img-preview > img {
  max-width: 100%;
}
.preview-sm {
  height: 2.25rem;
  width: 4rem;
  background-color: #f1f1f1;
  border: 1px solid #eee;
  box-sizing: border-box;
}
</style>
